package com.a1502d.todaynews;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.igexin.sdk.Tag;

import java.io.File;

/**
 * PushManager 为对外接口, 所有调用均是通过 PushManager.getInstance() 日志过滤器输入 PushManager, 在接口调用失败会有对应 Error 级别
 * log 提示.
 */
public class GetuiSdkDemoActivity extends FragmentActivity {

    private static final String TAG = "GetuiSdkDemo";
    private String appkey = "";
    private String appsecret = "";
    private String appid = "";

    private Context context;

    TextView appKeyView;
    TextView appSecretView;
    TextView masterSecretView;
    TextView appIdView;

    public static TextView tView;

    protected void initView() {
        tView = (TextView) findViewById(R.id.tvclientid);
        appKeyView = (TextView) findViewById(R.id.tvappkey);
        appSecretView = (TextView) findViewById(R.id.tvappsecret);
        masterSecretView = (TextView) findViewById(R.id.tvmastersecret);
        appIdView = (TextView) findViewById(R.id.tvappid);
    }

    private static final int REQUEST_PERMISSION = 0;

    // DemoPushService.class 自定义服务名称, 核心服务
    private Class userPushService = DemoPushService.class;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = this;
        initView();

        Log.d(TAG, "initializing sdk...");
        //集成个推开始，大家开发的时候把下面的代码集成到项目中既可以
        parseManifests();//获取清单文件中的变量数据
        if (checkPermission()) {//权限检测，申请
            requestPermission();
        } else {
            initPush();//初始化注册服务
        }
        // 检查 so 是否存在
        Log.e(TAG, "libgetuiext2.so exist = " + checkSO());
        //个推集成结束

        //获取用户信息之后，在进行别名的绑定，或设置TAG
        //别名一般情况下是自己用户系统的用户ID，命名不要数字开始
        PushManager.getInstance().bindAlias(GetuiSdkDemoActivity.this, "android1");


    }

    /**
     * 判断网络是否连接.
     */
    protected boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return mNetworkInfo != null && mNetworkInfo.isAvailable();
    }

    /**
     * 第一步：Android 6.0版本 权限检测
     *
     * @return
     */
    private boolean checkPermission() {
        PackageManager pkgManager = getPackageManager();
        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        return Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission;
    }

    /**
     * 申请权限
     */
    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    /**
     * 权限申请结果处理
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                initPush();
            } else {
                Log.e(TAG, "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                        + "functions will not work");
                initPush();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 第二步：初始化推送服务，注册推送服务，服务正常运行的前提
     */
    private void initPush() {
        // PushManager.getInstance().initialize(this.getApplicationContext(), null);//使用标准个推 SDK Service
        PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);//使用自定义Service

        // 注册 intentService 后 PushDemoReceiver 无效, sdk 会使用 DemoIntentService 传递数据,
        // AndroidManifest 对应保留一个即可(如果注册 DemoIntentService, 可以去掉 PushDemoReceiver, 如果注册了
        // IntentService, 必须在 AndroidManifest 中声明)
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    /**
     * 第三步：检测SO文件是否存在
     *
     * @return
     */
    private boolean checkSO() {
        File file = new File(this.getApplicationInfo().nativeLibraryDir + File.separator + "libgetuiext2.so");
        return file.exists();
    }

    /**
     * 测试addTag接口.
     */
    private void addTag(Tag[] tags) {
        PushManager.getInstance().setTag(context, tags, "" + System.currentTimeMillis());

    }

    /**
     * 获取个推SDK版本号
     */
    private void getVersion() {
        String version = PushManager.getInstance().getVersion(this);
        Toast.makeText(this, "当前sdk版本 = " + version, Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取CID
     */
    private void getCid() {
        String cid = PushManager.getInstance().getClientid(this);
        Toast.makeText(this, "当前应用的cid = " + cid, Toast.LENGTH_LONG).show();
        Log.d(TAG, "当前应用的cid = " + cid);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取清单文件中的定义变量
     */
    private void parseManifests() {
        String packageName = getApplicationContext().getPackageName();
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                //取值
                appid = appInfo.metaData.getString("PUSH_APPID");
                appsecret = appInfo.metaData.getString("PUSH_APPSECRET");
                appkey = appInfo.metaData.getString("PUSH_APPKEY");
                String string = appInfo.metaData.getString("PUSH_MASTERSECRET");

                //更新UI
                appKeyView.setText(String.format("%s", getResources().getString(R.string.appkey) + appkey));
                appSecretView.setText(String.format("%s", getResources().getString(R.string.appsecret) + appsecret));
                masterSecretView.setText(String.format("%s", getResources().getString(R.string.mastersecret) + string));
                appIdView.setText(String.format("%s", getResources().getString(R.string.appid) + appid));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置静默时间段
     */
    private void setSilentime(String b, String d) {
        try {
            //这里才是执行设置静默时段的代码
            int beginHour = Integer.valueOf(b);
            int durationHour = Integer.valueOf(d);
            boolean result = PushManager.getInstance().setSilentTime(context, beginHour, durationHour);

            if (result) {
                Toast.makeText(context, "begin = " + beginHour + ", duration = " + durationHour, Toast.LENGTH_SHORT).show();
                Log.d(TAG, "setSilentime, begin = " + beginHour + ", duration = " + durationHour);
            } else {
                Toast.makeText(context, "setSilentime failed, value exceeding", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "setSilentime failed, value exceeding");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解除别名绑定
     */
    private void unBindAlias(String alias) {
        PushManager.getInstance().unBindAlias(GetuiSdkDemoActivity.this, alias, false);
    }

    /**
     * 绑定别名
     */
    private void bindAlias(String alias) {
        PushManager.getInstance().bindAlias(GetuiSdkDemoActivity.this, alias);
    }

}
